<template>
  <div class="users">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索框及添加用户按钮 -->
    <div>
      <el-input placeholder="请输入内容" v-model="searchInfo" class="search-input" @keydown.native.enter="searchUser">
        <el-button slot="append" icon="el-icon-search" @click="searchUser"></el-button>
      </el-input>
      <el-button type="primary" plain @click="addData">添加用户</el-button>
    </div>
    <!-- 表格 -->
    <el-table
      class="mb-15 mt-15"
      border
      :data="userList"
      stripe
      style="width: 100%"
      highlight-current-row
      v-loading="loading">
      <el-table-column
        type="index"
        label="编号"
        width="50">
      </el-table-column>
      <el-table-column
        prop="username"
        label="姓名">
      </el-table-column>
      <el-table-column
        prop="email"
        label="邮箱"
        min-width="130">
      </el-table-column>
      <el-table-column
        prop="mobile"
        label="电话">
      </el-table-column>
      <el-table-column label="切换状态" width="80">
      <template slot-scope="scope">
        <el-switch
          v-model="scope.row.mg_state"
          active-color="#409eff"
          inactive-color="#cccccc"
          @change="handleState(scope.row)">
        </el-switch>
      </template>
      </el-table-column>
      <el-table-column label="操作" width="190">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" plain size="small" @click="editBtn(scope.row)"></el-button>
          <el-button type="warning" icon="el-icon-success" plain size="small" @click="handleGrant(scope.row)"></el-button>
          <el-button type="danger" icon="el-icon-delete" plain size="small" @click="deleteBtn"></el-button>
          <!-- 删除弹出框 -->
          <el-dialog
              title="提示"
              :visible.sync="delLogVisible"
              width="30%">
              <span>确认删除这条信息吗？</span>
              <span slot="footer" class="dialog-footer">
                <el-button @click="delLogVisible = false">取 消</el-button>
                <el-button type="primary" @click="delTrue(scope.row)">确 定</el-button>
              </span>
            </el-dialog>
        </template>
      </el-table-column>
    </el-table>

  <!-- 分页 -->
  <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="1"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
   </el-pagination>

   <!-- 添加用户弹出层 -->
   <el-dialog title="添加用户" :visible.sync="addLogFormVisible">
      <el-form :model="addForm" :rules="myrules" ref="addRef">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" type="password" :label-width="formLabelWidth" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addLogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addTrue('addRef')">确 定</el-button>
      </div>
    </el-dialog>
   <!-- 修改用户弹出层 -->
   <el-dialog title="修改用户" :visible.sync="editLogFormVisible">
      <el-form :model="editForm" :rules="myrules" ref="editRef">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editLogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editTrue('editRef')">确 定</el-button>
      </div>
    </el-dialog>
   <!-- 修改用户权限 -->
   <el-dialog title="修改用户权限" :visible.sync="grantLogFormVisible">
      <el-form :model="grantForm" :rules="myrules" ref="grantRef">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input v-model="grantForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="选择角色" :label-width="formLabelWidth">
          <el-select v-model="grantForm.rid" placeholder="请选择">
            <el-option
              v-for="(item,index) in roleList"
              :key="index"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="grantLogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="grantTrue('grantRef')">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {userData, delUser, addUser, toggleState, editUser, roleList, roleChange} from '@/api'
export default {
  data () {
    const checkEmail = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('邮箱不能为空'))
      }
      // eslint-disable-next-line
      let myreg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/
      if (myreg.test(value)) {
        callback()
      } else {
        return callback(new Error('邮箱格式错误，请重新输入'))
      }
    }
    return {
      loading: true,
      searchInfo: '', // 双向绑定的搜索关键词
      userList: [], // 用户列表
      currentPage: 1, // 当前页码默认为第一页,
      pagesize: 5, // 每页显示多少条
      total: 0, // 总条数
      delLogVisible: false, // 控制删除弹出框
      addLogFormVisible: false, // 控制添加弹出框
      editLogFormVisible: false, // 控制修改弹出框
      grantLogFormVisible: false, // 控制修改弹出框
      formLabelWidth: '120px',
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editForm: {
        username: '',
        email: '',
        mobile: ''
      },
      grantForm: {
        username: '',
        id: '',
        rid: ''
      },
      roleList: [],
      myrules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        email: [
          // 通过validator自定义校验，后面跟一个函数
          { required: true, validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '电话不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.renderList()
  },
  methods: {
    // 切换每页展示多少条数据
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.pagesize = val
      this.renderList()
    },
    // 切换页数
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.currentPage = val
      this.renderList()
    },
    // 渲染列表
    renderList () {
      userData({ query: this.searchInfo, pagenum: this.currentPage, pagesize: this.pagesize })
        .then(res => {
          if (res.meta.status === 200) {
            // console.log(res)
            this.userList = res.data.users
            this.total = res.data.total
            setTimeout(() => {
              this.loading = false // 获取完数据之后，让加载动画消失
            }, 1000)
          }
        })
    },
    // 搜索
    searchUser () {
      this.renderList()
    },
    // 删除
    deleteBtn () {
      this.delLogVisible = true
    },
    // 删除弹出框
    delTrue (row) {
      delUser(row.id)
        .then(res => {
          // console.log(res)
          if (res.meta.status === 200) {
            this.renderList()
            this.delLogVisible = false
            this.$notify({
              title: '删除成功',
              message: '您已经成功删除该条数据',
              type: 'success',
              offset: 100
            })
          }
        })
    },
    // 添加弹出层
    addData () {
      this.addLogFormVisible = true
    },
    // 确认添加
    addTrue (formName) {
      this.$refs[formName].validate((valide) => {
        if (valide) {
          addUser(this.addForm)
            .then(res => {
              if (res.meta.status === 201) {
                this.renderList()
                this.addForm.username = ''
                this.addForm.password = ''
                this.addForm.email = ''
                this.addForm.mobile = ''
                this.addLogFormVisible = false
                this.$notify({
                  title: '创建成功',
                  message: '您已经成功创建账户',
                  type: 'success',
                  offset: 100
                })
              }
            })
        }
      })
    },
    // 切换用户状态
    handleState (row) {
      let obj = {
        id: row.id,
        state: row.mg_state
      }
      toggleState(obj)
        .then(res => {
          if (res.meta.status === 200) {
            this.$notify({
              title: '操作成功',
              message: res.meta.msg,
              type: 'success',
              offset: 100
            })
          } else {
            this.$notify({
              title: '操作成功',
              message: res.meta.msg,
              type: 'error',
              offset: 100
            })
          }
        })
    },
    // 修改用户弹窗
    editBtn (row) {
      this.editLogFormVisible = true
      this.editForm.username = row.username
      this.editForm.email = row.email
      this.editForm.mobile = row.mobile
      this.editForm.id = row.id
    },
    // 提交编辑
    editTrue (formName) {
      this.$refs[formName].validate((value) => {
        if (value) {
          editUser(this.editForm)
            .then(res => {
              if (res.meta.status === 200) {
                this.editLogFormVisible = false
                this.renderList()
                this.$notify({
                  title: '操作成功',
                  message: res.meta.msg,
                  type: 'success',
                  offset: 100
                })
              } else {
                this.$notify({
                  title: '操作失败',
                  message: res.meta.msg,
                  type: 'success',
                  offset: 100
                })
              }
            })
        } else {
          this.$message.warning('字段校验不通过，请重新填写')
        }
      })
    },
    // 用户权限弹窗+渲染
    handleGrant (row) {
      // console.log(row)
      this.grantLogFormVisible = true
      this.grantForm.username = row.username
      this.grantForm.id = row.id
      this.grantForm.rid = row.role_name
      roleList()
        .then(res => {
          // console.log(res)
          this.roleList = res.data
        })
    },
    // 修改用户权限
    grantTrue (formName) {
      roleChange(this.grantForm)
        .then(res => {
          if (res.meta.status === 200) {
            this.grantLogFormVisible = false
            this.$notify({
              title: '操作成功',
              message: res.meta.msg,
              type: 'success',
              offset: 100
            })
          }
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.search-input {
    width: 330px;
    margin-bottom: 20px;
  }
</style>
